package com.volcreate.inn.controller;


import com.volcreate.inn.po.User;
import com.volcreate.inn.service.impl.BlogService;
import com.volcreate.inn.service.impl.CommentService;
import com.volcreate.inn.service.impl.UserService;
import com.volcreate.inn.utils.MyRandom;
import com.volcreate.inn.vo.CommentVO;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zxc
 * @since 2020-08-23
 */
@Controller
public class CommentController {
    private final CommentService commentService;
    private final BlogService blogService;
    private final UserService userService;

//    @Value("${comment.avatar}")
//    private String avatar;

    public CommentController(CommentService commentService, BlogService blogService, UserService userService) {
        this.commentService = commentService;
        this.blogService = blogService;
        this.userService = userService;
    }

    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable Long blogId, Model model) {
        model.addAttribute("comments", commentService.listByBlogIdAndIsRootComment(blogId));
        return "blog :: commentList";
    }


    @PostMapping("/comments")
    public String post(CommentVO commentVO, HttpSession session) {


        // 通过提交过来的blog.id查找到blog。
        Long blogId = commentVO.getBlog().getId();
        if (commentVO.getBlog().getCommentable()) {
            // 设置blog
            commentVO.setBlogId(blogId);
            // ParentCommentId 在 save 方法实现
            User user = (User) session.getAttribute("user");
            if (user != null){
                commentVO.setUserId(user.getId());
            }else {
                commentVO.setUserId(MyRandom.randX(2,9));
            }
            // 保存comment
            if (commentVO.getParentCommentId() == -1){
                commentVO.setParentCommentId(null);
            }
            if (commentVO.getRootCommentId() == -1){
                commentVO.setRootCommentId(null);
            }
            commentService.save(commentVO);
        }


        return "redirect:/comments/" + blogId;
    }
}

